package com.aaa.util;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/* *
 *类名：AlipayConfig
 *功能：基础配置类
 *详细：设置帐户有关信息及返回路径
 *修改日期：2017-04-05
 *说明：
 *以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
 */

public class AlipayConfig {

//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    public static String app_id = "2021000116673458";

    // 商户私钥，您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC2CFdan366aT2W5Wg7KS4fk1qXyLxINIxinf64q2cGbImx4WFhic7P6DgBjONGpv2+rYdabfFws7ZeyHip4svbn5hb3+IfQHVjvHpX/Dg95tY2YY4oDZBidmAIMIUyerfcXOOUD0Koe1oBpsTqABO08kyKqrbazaO0BUdKL6SpBQoZdLkF/oZdmMck+HRGEobdp8ecxBcgDSsSzm6MIF7q5n9rXEm7BS+pE9SHo8vnKkN1OdgfaKgGrBSoJ52KanXQPd0bQnFS6k7qwKaKtbs9S526E2ULocEq4I6OcjtkSHEXIiSDRC291uHoFW/sWPI9JkfB9KWcTtIlQtUA9K77AgMBAAECggEBAIfVYZn2OpLPxW28cjLzX7+gLZHl8NnQnJFaZKFZBd/9TiK2k/w84V6zYleF0nL+WYrX4pDQScJX2FaSMbhTzNtuFDs6rXm0l+R82K6fPzix8FdUJMgulvdibfaufjZU7K47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s77dKE1Ea";

    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkIJH63J6PF398Xkx0mOU0kuRZW8rsMrVdgEJ+mrX4ATvDLe7QxYiaARSRIuDjBpovg2WyjzmVkgOv2+bHtkMOP0HigsnsASse5u05h+WdUNAYTg07+pix58EoZpiDp+9Ct81eGT9AISpYHUHXhdGVCy3t58DCv1+YCzgueeoP8YWSEY5wZFHdyodceTaA7Z9X3RFkLSJTdnK4d5LWURHJWqyzQKQdf3WyqqbjKFwWJJjsgzmlZ6/DevIJ2VC+DrWqH2xqvGf8uPPKVxxfs7hJBmBUpW7yA+h8bQvK8SC+sGXO5yXtGiirjerdbtS5WXxgtupHKgC/U4GJEQfMVRoswIDAQAB";

    // 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，支付包要进行发送Post请求所以必须外网可以正常访问  修改数据状态使用
    public static String notify_url = "http://i7zv4c.natappfree.cc/pay/notifyPay";

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，内网或者外网  支付成功返回页面
    public static String return_url = "http://localhost:8090/pay/return";

    // 签名方式
    public static String sign_type = "RSA2";

    // 字符编码格式
    public static String charset = "utf-8";

    // 支付宝网关
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    // 支付宝日志生成
    public static String log_path = "C:\\";


//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑




    /**
     * 调用支付宝接口    需要支付宝支付的时候调用此方法
     * @param map 传入需要的数据
     * @return java.lang.String
     */
    /*public static String aliPayPort(Map<String,Object> map){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        Map<String,Object> pay=new HashMap<>();
        pay.put("out_trade_no",map.get("orderId"));
        pay.put("product_code","FAST_INSTANT_TRADE_PAY");
        pay.put("total_amount",map.get("shopMoney"));
        pay.put("subject","FM");
        pay.put("body","Iphone6 16G");
        alipayRequest.setBizContent(JSON.toJSONString(pay));
        String result = "";
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }*/






    /**
     * 获取返回的数据信息
     *
     * @param request 获取的http请求
     * @return java.util.Map;
     * @throws UnsupportedEncodingException :字符编码转换异常抛出
     */
    public static Map<String, String> signVerified(HttpServletRequest request) throws UnsupportedEncodingException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (
                Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }


    /**
     * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
     *
     * @param sWord 要写入日志里的文本内容
     */
    public static void logResult(String sWord) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis() + ".txt");
            writer.write(sWord);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

